﻿#include "additem.h"

AddItem::AddItem(const QStringList &topics_,
                 QWidget *parent) :
    QDialog(parent)
{
    setupUi(this);

    table=G_ENTITY;
    topics=topics_;
}

void AddItem::on_btn_paste_clicked()
{
    QString label=qApp->clipboard()->text().trimmed();
    if(!label.isEmpty())
        in_label->setText(label);
}

bool AddItem::addItem(const QString &topic,
                      const QString &label,
                      const QString &detail)
{
    QSqlQuery query;
    query.prepare(QString("insert into %1 (topic,label,detail) "
                          "values (?,?,?)")
                  .arg(table));
    query.addBindValue(topic);
    query.addBindValue(label);
    query.addBindValue(detail);
    if(query.exec())
        return true;
    else
    {
        qDebug() << query.lastError().text();
        return false;
    }
}

QString AddItem::checkFirst(const QString &label)
{
    if(!topics.isEmpty())
    {
        foreach (QString topic, topics) {
            if(label.contains(topic,Qt::CaseInsensitive))
                return topic;
        }
    }

    if(label.contains("-"))
        return label.split("-").first();
    else if(label.contains(" "))
        return label.split(" ").first();
    else if(label.contains("_"))
        return label.split("_").first();
    else
        return label.left(4);
}

void AddItem::on_btn_submit_clicked()
{
    QString label=in_label->text().trimmed();
    if(label.isEmpty())
    {
        MESSAGE_DETAIL_EMPTY
    }

    QString detail=in_detail->text().trimmed();
    if(detail.isEmpty())
        detail="F";

    QString topic=in_topic->text().trimmed();
    if(topic.isEmpty())
        topic=checkFirst(label);

    if(addItem(topic,label,detail.toUpper()))
        accept();
    else
        MESSAGE_CANNOT_SUBMIT
}

void AddItem::on_btn_clean_clicked()
{
    in_topic->clear();
}

void AddItem::on_in_label_editingFinished()
{
    QString label=in_label->text().trimmed();
    if(label.isEmpty())
        return;

    in_topic->setText(checkFirst(label));
}
